// *****************************************************
// Aitrox Information Technology
// http://www.proxima-ai.com
// Copyright 2021 Aitrox. All rights reserved.
//
// Filename: download.go
// CreateDate: 2023-05-06
// Author: zjp
// Description: 下载文件
// ******************************************************
package service

import (
	"fmt"
	"os"
	"usplatformserver/global"
	"usplatformserver/internal/dao"
	"usplatformserver/internal/model"
	"usplatformserver/pkg/errcode"
)

type DownloadRequest struct {
	OrganType *int   `form:"organType" binding:"required"`
	ID        *int   `form:"id" binding:"required"`
	FileName  string `form:"fileName" binding:"required"`
}

type DownloadCommonRequest struct {
	OrganType *int `form:"organType" binding:"required"`
}

type DeleteFilesRequest struct {
	OrganType *int   `form:"organType" binding:"required"`
	Files     string `form:"files" binding:"required"`
}

/**
 * @brief 初始化待下载文件个数
 * @param counts-待下载文件个数
 * @return 错误信息
 */
func InitWaitDownloadCount() (map[int]int, error) {
	var counts = make(map[int]int)
	dao := dao.New(global.DBEngine)
	var ret []*model.WaitDownloadCount = []*model.WaitDownloadCount{}

	ret, err := dao.GetWaitDownloadTypeCount()
	if err != nil {
		return counts, err
	}
	for _, v := range ret {
		counts[v.OrganType] = v.WaitDownloadTimes
	}

	fmt.Println(counts)

	return counts, nil
}

/**
 * @brief 获取待下载文件个数
 * @param organType-检查部位
 */
func GetWaitDownloadCount(organType int) (int, error) {
	dao := dao.New(global.DBEngine)
	count, err := dao.GetWaitDownloadCount(organType)
	if err != nil {
		return 0, err
	}
	return count, nil
}

/**
 * @brief 通过检查部位获取下载文件信息
 * @param organType-检查部位
 * @return 检查文件信息列表，错误信息
 */
func (svc *Service) GetDownloadFileList(organType int) ([]*model.Download, error) {
	return svc.dao.GetDownloadFileList(organType)
}

/**
 * @brief 插入下载文件数据
 * @param organType-检查部位
 * @param fileName-文件名
 * @return 错误信息
 */
func InsertDownloadFile(organType int, fileName string) error {
	dao := dao.New(global.DBEngine)
	return dao.InsertDownloadFile(organType, fileName)
}

/**
 * @brief 更新下载次数
 * @param id-下载文件信息唯一ID
 * @return 错误信息
 */
func UpdateDownloadTimes(id int) error {
	dao := dao.New(global.DBEngine)
	return dao.UpdateDownloadTimes(id)
}

/**
 * @brief 删除下载文件
 * @param organType-检查部位
 * @param fileNames-文件名列表
 * @return 影响条数，错误信息
 */
func (svc *Service) DeleteDownloadFiles(organType int, fileNames []string) (int, error) {
	return svc.dao.DeleteDownloadFiles(organType, fileNames)
}

/**
 * @brief 下载
 * @param param-入参
 * @return 错误信息
 */
func (s *Service) Download(param *DownloadRequest) *errcode.Error {
	path := fmt.Sprintf("./%s", param.FileName)
	file, err := os.Open(path)

	if os.IsNotExist(err) {
		return errcode.DownloadFileNotExist
	}
	if err != nil {
		global.Logger.Infof("download failed: %v", err)
		return errcode.DownloadFail
	}
	file.Close()

	return nil
}
